package com.project.controller;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RequestMapping("user")
@RestController
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("login")
    public String login(String userName, String pwd, HttpServletRequest req){
        if (userService.login(userName, pwd) == null){
            return "登录失败";
        }
        else {
            //在session中，保存登陆信息
            req.getSession().setAttribute("loginUser",userService.login(userName,pwd));
            return "登录成功";

        }
    }

    @RequestMapping("reg")
    public String reg(String username,String pwd,String repeatPwd,String email,String imgPath){
        if (userService.findByName(username) != null){
            return "用户名已存在!";
        }
        else if (username.length()> 10 || username.length()< 1){
            return "用户名长度违规！";
        } else if (pwd.length() < 1 || pwd.length()>10) {
            return "密码长度违规!";
        }
        else if (!pwd.equals(repeatPwd)){
            return "两次密码不一致!";
        } else if (!email.matches("\\b[\\w.%+-]+@[\\w.-]+\\.[a-zA-Z]{2,6}\\b")) {
            return "邮箱不规范!";
        }
        else {
            userService.addUser(new UserBean(username,pwd,email,imgPath));
            return "ok";
        }
    }

    @RequestMapping("getLoginUser")
    public UserBean getLoginUser(HttpServletRequest req){
        return (UserBean)req.getSession().getAttribute("loginUser");
    }
}
